<?php


namespace App\Libs\Contracts\Push\Oppo;


use App\Libs\httpUtil;
use App\Models\User;

class OppoPushService
{

    private $appSecret = "dd66a54dd45d4c8d8702b19ad64c2aff";

    private $app_key = "0c0f3793a13f4a85800f31373ffa42b7";

    private $mastersecret = "918da2957e1f487cb26c77e239d6a288";

    public function push($title, $content, $userId)
    {

        $deviceTokenList = [];
        if ($userId) {
            $user = User::find($userId);
            if ($user['pushType'] == "OPPO") {
                if ($user['type'] == "ANDROID") {
                    $deviceTokenList[] = $user['registrationId'];
                }
            }
        } else {
            $user = User::select("registrationId")->where(['pushType' => "OPPO", 'type' => "ANDROID"])->get()->toArray();
            foreach ($user as $value) {
                $deviceTokenList[] = $value['registrationId'];
            }
        }
        if(count($deviceTokenList) != 0 ){
            $this->send($title, $content, $deviceTokenList);
        }

    }


    private function refreshAuthToken()
    {

        $http = new httpUtil();
        $url = "https://api.push.oppomobile.com/server/v1/auth";
        $param['app_key'] = $this->app_key;
        $param['timestamp'] = (float)msectime();
        $str = $param['app_key'] . $param['timestamp'] . $this->mastersecret;

        $param['sign'] = hash("sha256", $str);
        $result = $http->http_post($url, $param);
        if ($result) {
            $result = json_decode($result, true);
            $authToken = $result['data']['auth_token'];
            \RedisDB::setex(env("APP_NAME") . '-OPPO-authToken', 86400, $authToken);
            return $authToken;
        } else {
            \Log::error("获取OPPER authToken失败");
            \Log::error($result);
            return "";
        }
    }

    private function getAuthToken()
    {
        $authToken = \RedisDB::get(env("APP_NAME") . '-OPPO-authToken');
        if ($authToken) {
            return $authToken;
        } else {
            return $this->refreshAuthToken();
        }
    }

    public function send($title, $content, $device_token_list)
    {
        $http = new httpUtil();
        $parameters = ["data" => "", "type" => ""];
        $intent = "com.xszb.kangtaicloud.ui.message.MessageListActivity";
        if (count($device_token_list) == 1) {//单推
            \Log::info("OPPO推送");
            $messageData = [
                'target_type' => 2,
                'target_value' => implode(';', $device_token_list),
                'notification' => [
                    'app_message_id' => uniqid(),
                    'title' => $title,
                    'content' => $content,
                    'click_action_type' => 4,
                    'click_action_activity' => $intent,
                    'action_parameters' => $parameters,
                    'off_line_ttl' => 86400 * 3
                ]
            ];
            $postData = [
                'message' => json_encode($messageData)
            ];
            $url = 'https://api.push.oppomobile.com/server/v1/message/notification/unicast';
            $res = $http->request($url, $postData, ['Content-Type:application/x-www-form-urlencoded; charset=utf-8', 'auth_token:' . $this->getAuthToken()], TRUE);
            \Log::info($res);
            return true;
        } elseif (count($device_token_list) > 1) {
            \Log::info("OPPO推送");
            $url = "https://api.push.oppomobile.com/server/v1/message/notification/save_message_content";
            $messageBody = [
                'app_message_id' => uniqid(),
                'title' => $title,
                'content' => $content,
                'click_action_type' => 4,
                'click_action_activity' => $intent,
                'action_parameters' => $parameters,
                'off_line_ttl' => 86400 * 3,
            ];

            $res = $http->request($url, $messageBody, ['Content-Type:application/x-www-form-urlencoded; charset=utf-8', 'auth_token:' . $this->getAuthToken()], TRUE);
            $messageId = null;
            if ($res && $res['code'] == 0 && isset($res['data']['message_id'])) {
                $messageId = $res['data']['message_id'];
            }

            $url = "https://api.push.oppomobile.com/server/v1/message/notification/broadcast";
            $regidParams = array_chunk($device_token_list, 1000);
            foreach ($regidParams as $k => $v) {
                $postData = [
                    'message_id' => $messageId,
                    'target_type' => 2,
                    'target_value' => implode(';', $v)
                ];
                $res = $http->request($url, $postData, ['Content-Type:application/x-www-form-urlencoded; charset=utf-8', 'auth_token:' . $this->getAuthToken()], TRUE);
                \Log::info($res);
            }
            return true;
        }
    }

}